//
//  animation.cpp
//  Sinnca Engine v2
//
//  Created by Ryan Oldis on 10/25/11.
//  Copyright (c) 2011 Sinnca Studios. All rights reserved.
//

#include "animation.h"

animation::animation(std::string n)
{
	name = n;
	
	playing = true;
	currentFrame = 1;
}



static int newAnimation(lua_State* L)
{
	int n = lua_gettop(L);
	if (n != 2)
	{
		return luaL_error(L, "You need to name this animaition...");
	}
	
	luaL_checktype(L, 1, LUA_TTABLE);
	
	
	lua_newtable(L);
	
	lua_pushvalue(L, 1);
	lua_setmetatable(L, -2);
	
	lua_pushvalue(L, 1);
	lua_setfield(L, 1, "__index");
	
	
	animation** ani = (animation**)lua_newuserdata(L, sizeof(animation*));
	*ani = new animation(luaL_checkstring(L, 2));
	
	
	luaL_getmetatable(L, "animation");
	lua_setmetatable(L, -2);
	
	lua_setfield(L, -2, "__self");
	
	
	lua_setglobal(L, luaL_checkstring(L, 2));
	
	
	return 1;

}


animation* checkAni(lua_State* L, int ind)
{
	void* ud = 0;
	
	// check for table object
	luaL_checktype(L, ind, LUA_TTABLE);
	
	// push the key we're looking for (in this case, it's "__self")
	lua_pushstring(L, "__self");
	// get our table
	lua_gettable(L, ind);
	
	// cast userdata pointer to "Node" type
	ud = dynamic_cast<animation*>((animation*)lua_touserdata(L, -1));
	luaL_argcheck(L, ud != 0, ind, "Need 'Animation' type...");
	
	return *((animation**)ud);
}


static int newFrame(lua_State*L)
{
	int n = lua_gettop(L);
	animation* ani;
		
	keyframe key;
	
	if (n == 5)
	{
		ani = checkAni(L, 1);
		
		key.texco[0] = lua_tonumber(L, 2);
		key.texco[1] = lua_tonumber(L, 3);
		key.texco[2] = lua_tonumber(L, 4);
		key.texco[3] = lua_tonumber(L, 5);
		
		ani->timeline.push_back(key);
	}
	
	return 0;
}

/*
static const luaL_Reg animationGc[] = {
	
	{"__gc",},
	{NULL, NULL}
};
 */
static const luaL_Reg animationFuncs[] = {
	
	{"new", newAnimation},
	{"newFrame", newFrame},
	{NULL, NULL}
};

void registerAnimation(lua_State* L)
{
	luaL_newmetatable(L, "animation");
	
	//luaL_register(L, 0, animationGc);
	luaL_register(L, 0, animationFuncs);
	lua_pushvalue(L, -1);
	
	lua_setfield(L, -2, "__index");
	
	
	
	luaL_register(L, "animation", animationFuncs);
}


